package com.suxin.validator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.*;

/**
 * @author Tang
 * @classname JavaxValidator
 * @description [  ]
 * @date 2023/1/7 14:46
 */
public class JavaxValidator implements ValidatorInterface {

    private final static Validator VALIDATOR;

    static {
        VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
    }

    @Override
    public Map<String, String> validatorBean(Object bean, Class<?>[] groupClass) {
        Map<String, String> errorMsgMap = new HashMap<>(8);
        Set<ConstraintViolation<Object>> validate = VALIDATOR.validate(bean, groupClass);
        validate.forEach(item -> {
            errorMsgMap.put(item.getPropertyPath().toString(), item.getMessage());
        });
        return errorMsgMap;
    }

    @Override
    public String validateProperty(Object bean,String name,Class<?>[] groupClass) {
        Set<ConstraintViolation<Object>> validate = VALIDATOR.validateProperty(bean, name, groupClass);
        return Optional.ofNullable(new ArrayList<>(validate).get(0))
                .map(ConstraintViolation::getMessage)
                .orElseGet(null);
    }

    @Override
    public Map<String, String> validatorBean(Object bean) {
        return validatorBean(bean, new Class<?>[]{Default.class});
    }

    @Override
    public String validateProperty(Object bean,String name) {
        return validateProperty(bean,name,new Class<?>[]{Default.class});
    }
}
